package com.gbx.ximalayating.fragment;


import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.gbx.ximalayating.R;
import com.gbx.ximalayating.activity.ClassifyActivity;
import com.gbx.ximalayating.activity.ClassifyImgActivity;
import com.gbx.ximalayating.adapter.ClassifyAdapter;
import com.gbx.ximalayating.adapter.FootPagerAdapter;
import com.gbx.ximalayating.application.BaseApplication;
import com.gbx.ximalayating.entity.CCEntity;
import com.gbx.ximalayating.entity.ClassifyEntity;
import com.gbx.ximalayating.entity.FCEntity;
import com.gbx.ximalayating.entity.FootEntity;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class ClassifyFragment extends Fragment {
    private RecyclerView recycler;
    private ClassifyAdapter classifyAdapter;
    private ScrollView scroll;
    private ImageView classifyImg;
    private ViewPager footVP;
    private FootPagerAdapter footPagerAdapter;
    private List<ImageView> mImageViews;
    private List<CCEntity> list;

    private List<CCEntity> imgList;
    private final int WHAT_KEY=1;
    private Timer timer;
    private TimerTask task;
    private int curPosition = 0;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //刷新UI
            switch (msg.what){
                case WHAT_KEY:
                    if (curPosition==3){
                        curPosition=0;
                    }else {
                        curPosition++;
                        footVP.setCurrentItem(curPosition);
                    }
                        break;
            }

        }
    };

    public ClassifyFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_classify, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable final Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        scroll = ((ScrollView) view.findViewById(R.id.classify_fragment));
        classifyImg = ((ImageView) view.findViewById(R.id.classify_img));
        recycler = (RecyclerView) view.findViewById(R.id.recycler);
        recycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
        classifyAdapter = new ClassifyAdapter(getContext());
        forceStopRecyclerViewScroll(recycler);
        imgList = new ArrayList<>();
        BaseApplication application = (BaseApplication) getActivity().getApplication();
        application.getClassifyService().getList().enqueue(new Callback<ClassifyEntity>() {


            @Override
            public void onResponse(Call<ClassifyEntity> call, Response<ClassifyEntity> response) {
                if (response != null) {
                    ClassifyEntity body = response.body();
                    if (body != null) {
                        list = body.getList();
                        imgList.add(list.get(0));
                        Picasso.with(getContext()).load(ClassifyFragment.this.list.get(0).getCoverPath()).into(classifyImg);
                        ClassifyFragment.this.list.remove(0);
                        classifyAdapter.addAll(ClassifyFragment.this.list);
                        recycler.setAdapter(classifyAdapter);
                    }

                }

            }

            @Override
            public void onFailure(Call<ClassifyEntity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });


        mImageViews = new ArrayList<>();
        footVP = ((ViewPager) view.findViewById(R.id.foot_vp));
        footPagerAdapter = new FootPagerAdapter(getContext());
        footVP.setAdapter(footPagerAdapter);
        application.getFootView().getData().enqueue(new Callback<FootEntity>() {
            @Override
            public void onResponse(Call<FootEntity> call, Response<FootEntity> response) {

                final List<FCEntity> data = response.body().getData();
//                Log.i("1471", data.toString());
                for (int i = 0; i < data.size(); i++) {
                    curPosition = i;
                    ImageView imageView = new ImageView(getContext());
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Picasso.with(getContext()).load(data.get(i).getCover()).into(imageView);
                    mImageViews.add(imageView);
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                             Toast.makeText(getContext(),"andalkndlan",Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getContext(),ClassifyActivity.class);
                            intent.putExtra("url",data.get(curPosition).getLink());
                            intent.putExtra("position",curPosition);
                            startActivity(intent);
                        }
                    });
                }
                ImageView imageView = new ImageView(getContext());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                Picasso.with(getContext()).load(data.get(0).getCover()).into(imageView);
                mImageViews.add(imageView);
                footPagerAdapter.addAll(mImageViews);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                             Toast.makeText(getContext(),"andalkndlan",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getContext(),ClassifyActivity.class);
                        intent.putExtra("url",data.get(0).getLink());
                        intent.putExtra("position",curPosition);
                        startActivity(intent);
                    }
                });

            }

            @Override
            public void onFailure(Call<FootEntity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        classifyAdapter.setListener(new ClassifyAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(int position, List<CCEntity> ccEntities) {
                Toast.makeText(getContext(),"大砍刀那；都那么单",Toast.LENGTH_SHORT).show();
                Log.i("1471","mndalkm");
                Intent intent = new Intent(getContext() , ClassifyImgActivity.class);
                intent.putExtra("title" , ccEntities.get(0).getTitle());
                startActivity(intent);
            }
        });

        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position = parent.getChildAdapterPosition(view);
                if (position == 0) {
                    outRect.set(0, 20, 0, 0);
                } else if (position == 1) {
                    outRect.set(0, 20, 0, 0);
                } else if (position % 6 == 0) {
                    outRect.set(0, 20, 0, 0);
                } else if (position % 6 == 1) {
                    outRect.set(0, 20, 0, 0);
                } else if (position == list.size()) {
                    outRect.set(0, 0, 0, 20);
                } else if (position == list.size() - 1) {
                    outRect.set(0, 0, 0, 20);
                }
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDrawOver(c, parent, state);
            }
        };
        recycler.addItemDecoration(decoration);
        classifyImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ClassifyImgActivity.class);
                intent.putExtra("url",imgList.get(0).getCoverPath());
                intent.putExtra("title" , imgList.get(0).getTitle());
                startActivity(intent);
            }
        });
        footVP.setCurrentItem(curPosition, false);
        footVP.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                curPosition = position;
//                Intent intent = new Intent(getContext() ,ClassifyActivity.class);
//                startActivity(intent);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_IDLE:
                        if (curPosition == mImageViews.size() - 1) {
                            footVP.setCurrentItem(0, false);
                        }
                        break;
                }
            }
        });
        timer=new Timer();
        task=new TimerTask() {
            @Override
            public void run() {

                Message msg=Message.obtain();
                msg.what=WHAT_KEY;
                handler.sendEmptyMessage(msg.what);
            }
        };
        timer.schedule(task,0,2000);
    }
    public  void forceStopRecyclerViewScroll(RecyclerView mRecyclerView) {
        mRecyclerView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0, 0, 0));
    }
}

